const tile = new ol.layer.Tile({
    source: new ol.source.XYZ({
        url: 'http://webrd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scale=1&style=8'
    })
})
const zoom = 4, center = ol.proj.fromLonLat([107.11040599933166, 34.26271532332011])
var map = new ol.Map({
    target: 'map',
    layers: [
        tile
    ],
    view: new ol.View({
        center,
        zoom
    })
});

class DrawTool {
    constructor(map) {
        this.map = map
        this.vectorSource = new ol.source.Vector({
            features: []
        })
        this.drawType = ''
        this.coords = []
        this.toolTipDom = document.createElement('div')
        this.toolTipDom.classList.add('tooltips')
        this.toolTip = new ol.Overlay({
            element: this.toolTipDom,
            positioning: 'center-left',
            offset: [5, 0]
        })
        this.map.addOverlay(this.toolTip)
        this.vectorLayer = new ol.layer.Vector({
            source: this.vectorSource,
            style: this._styleFunction
        })
        this.map.addLayer(this.vectorLayer)
    }

    _setDblClickZoom(active = true) {
        const dblClickInteraction = map
            .getInteractions()
            .getArray()
            .find(interaction => {
                return interaction instanceof ol.interaction.DoubleClickZoom
            })
        dblClickInteraction.setActive(active)
    }

    _registerMapEvt() {
        const that = this
        const clickFunction = (e) => {
            if(that.drawType === '') return
            const coord = e.coordinate
            that.coords.push(coord)
            if(that.drawType === 'point') {
                const geom = new ol.geom.Point(coord)
                const feature = new ol.Feature({
                    geometry: geom
                })
                that.vectorSource.addFeature(feature)
            }
        }
        const dblclickFunction = (e) => {
            if(that.drawType === '') return
            // dblclick会添加两次，删除一个
            if(that.drawType !== 'point') {
                that.coords.length = that.coords.length - 1
                let geom = null
                if(that.drawType === 'line') {
                    geom = new ol.geom.LineString(that.coords)
                } else if(that.drawType === 'polygon') {
                    that.coords.push(that.coords[0])
                    geom = new ol.geom.Polygon([that.coords])
                }
                const feature = new ol.Feature({
                    geometry: geom
                })
                that.vectorSource.clear()
                that.vectorSource.addFeature(feature)
            }
            that.drawType = ''
            setTimeout(() => {
                that.coords = []
                that.toolTip.setPosition(null)
                that._setDblClickZoom(true)
                that.map.un('click', clickFunction)
                that.map.un('pointermove', mousemoveFunction)
                that.map.un('dblclick', dblclickFunction)
            }, 100)
        }
        const mousemoveFunction = (e) => {
            if(that.drawType === '') return
            const coord = e.coordinate
            let coords = [...that.coords]
            coords.push(coord)
            that.toolTip.setPosition(coord)
            let tips = ''
            if(that.coords.length === 0) {
                tips = '点击地图开始绘制'
            } else {
                if(that.drawType === 'line') {
                    // 获取测量结果
                    const geom = new ol.geom.LineString(coords)
                    tips = '双击地图结束绘制'
                    const feature = new ol.Feature({
                        geometry: geom
                    })
                    that.vectorSource.clear()
                    that.vectorSource.addFeature(feature)
                } else if(that.drawType === 'polygon') {
                    that.vectorSource.clear()
                    if(that.coords.length < 2) {
                        tips = '点击地图继续绘制'
                        const geom = new ol.geom.LineString(coords)
                        const feature = new ol.Feature({
                            geometry: geom
                        })
                        that.vectorSource.addFeature(feature)
                    } else {
                        // 获取测量结果
                        coords.push(coords[0])
                        const geom = new ol.geom.Polygon([coords])
                        tips = '双击地图结束绘制'
                        const feature = new ol.Feature({
                            geometry: geom
                        })
                        that.vectorSource.addFeature(feature)
                    }
                } else {
                    tips = '双击地图结束绘制'
                }
            }
            that.toolTipDom.innerText = tips
        }
        that.map.on('click', clickFunction)
        that.map.on('pointermove', mousemoveFunction)
        that.map.on('dblclick', dblclickFunction)
    }

    _styleFunction(feat) {
        const image = new ol.style.Circle({
            radius: 3,
            stroke: new ol.style.Stroke({
                color: '#f00',
                width: 2
            }),
            fill: new ol.style.Fill({
                color: '#ffffff'
            })
        })
        const styles = [new ol.style.Style({
            image,
            stroke: new ol.style.Stroke({
                color: '#ff0000',
                width: 2
            }),
            fill: new ol.style.Fill({
                color: 'rgba(255,0,0,0.2)'
            })
        })]
        const geomType = feat.getGeometry().getType()
        let coords = feat.getGeometry().getCoordinates()
        if(geomType === 'Polygon') coords = coords[0]
        coords.forEach(coord => {
            styles.push(new ol.style.Style({
                geometry: new ol.geom.Point(coord),
                image
            }))
        })

        return styles
    }

    activeDraw(type = 'point') {
        this.drawType = type
        this.coords = []
        this.vectorSource.clear()
        this._registerMapEvt()
        this._setDblClickZoom(false)
    }
}


const tool = new DrawTool(map)
document.getElementById('point').onclick = () => {
    tool.activeDraw('point')
}
document.getElementById('line').onclick = () => {
    tool.activeDraw('line')
}
document.getElementById('polygon').onclick = () => {
    tool.activeDraw('polygon')
}
